﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using ANZ_AIM_DAL;
using ANZ_AIM_BLL.Model;
using ANZ_AIM_BLL.Utils;
using ANZ_AIM_FRAMEWORK;

namespace ANZ_AIM_BLL
{
    public class MailConfigBLL
    {
        private string ConnectionString;
        private const string TABLE_NAME = "MailConfig";
        private Dictionary<string, string> ObjectPropDict;

        public MailConfigBLL()
        {
            ConnectionString = DBHelper.GetMainMdbConnectionString();
            this.ObjectPropDict = BuildObjectPropertyMapping();
        }

        public MailConfig GetMailConfig()
        {
            try
            {
                var dict = MiscHelper.Clone(this.ObjectPropDict);

                string command = string.Format("SELECT ID, Branch, Floor, CreatedDate, LastUpdate FROM [{0}]", TABLE_NAME);
                OleDbDataReader reader = OleDbHelper.ExecuteReader(this.ConnectionString, CommandType.Text, command);
                List<MailConfig> mailconfigs = new List<MailConfig>();

                while (reader.Read())
                {
                    mailconfigs.Add(PopulateObjectHelper.PopulateMailConfigObject(reader));
                }
                reader.Close();
                return (mailconfigs.Count > 0 ? mailconfigs[0] : null);
            }
            catch (Exception ex) { throw; }
        }
        public void Save(MailConfig mailConfig)
        {
            try
            {
                var dict = MiscHelper.Clone(this.ObjectPropDict);
                OleDbParameter[] parameters;
                string command = string.Empty;
                if (string.IsNullOrEmpty(mailConfig.ID))
                {
                    command = CommandHelper.BuildInsertCommand(mailConfig, dict, out parameters);
                }
                else
                {
                    dict.Remove("ID");
                    var conditionDict = new Dictionary<string, string>
                    {
                        {"ID", "ID"}
                    };
                    command = CommandHelper.BuildUpdateCommand(mailConfig, dict, conditionDict, out parameters);
                }
                int n = OleDbHelper.ExecuteNonQuery(this.ConnectionString, CommandType.Text, command, parameters);
            }
            catch (Exception ex) { throw; }
        }

        public Dictionary<string, string> BuildObjectPropertyMapping()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>
            {
                {"ID", "ID"},
                {"Branch", "Branch"},
                {"Floor", "Floor"},
                {"CreatedDate", "CreatedDate"},
                {"LastUpdate", "LastUpdate"}
            };

            return dictionary;
        }

    }
}
